//
//  BookTextString.m
//  QiYReader
//
//  Created by 奇阅科技 on 14/11/27.
//  Copyright (c) 2014年 奇阅科技. All rights reserved.
//

#import "BookReadPermissions.h"
#import "LKDBHelper.h"
#import "PathHelper.h"
#import "BookChapterInfo.h"
#import "UserAccount.h"
@implementation BookReadPermissions
+(NSString *)getTableName
{
    return @"BookReadPermissions";
}
-(instancetype)init{
    self = [super init];
    if (self) {
        UserAccount *user = [UserAccount currentAccount];
        if (user) {
            self.uid = user.uid;
        }else{
            self.uid = @"love";
        }
    }
    return self;
}
#pragma mark - 更新阅读权限
-(void)updateBookReadPermissions{
    if (self.articleid.length<1||self.uid.length<1||self.chapterId.length<1) {
        NSLog(@"___________________________阅读权限参数不能为空");
        return;
    }
    BookReadPermissions *recharge = [BookReadPermissions searchSingleWithWhere:[NSString stringWithFormat:@"articleid='%@' AND uid='%@' AND chapterId='%@'",self.articleid,self.uid,self.chapterId] orderBy:nil];
    
    if (recharge) {
        [BookReadPermissions updateToDB:self where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@' AND chapterId='%@'",self.articleid,self.uid,self.chapterId]];//updateToDBWithSet:[NSString stringWithFormat:@"readPermissions='%d'",self.readPermissions] where:[NSString stringWithFormat:@"articleid='%@' AND uid='%@' AND chapterId='%@'",self.articleid,self.uid,self.chapterId]];
    } else {
        [BookReadPermissions insertToDB:self];
    }
}
#pragma mark 获取阅读权限
-(BOOL)getMyReadPermissions{
    if (self.articleid.length<1||self.uid.length<1||self.chapterId.length<1) {
        NSLog(@"___________________________阅读权限参数不能为空");
        return NO;
    }
    BookReadPermissions *recharge = [BookReadPermissions searchSingleWithWhere:[NSString stringWithFormat:@"articleid='%@' AND uid='%@' AND chapterId='%@'",self.articleid,self.uid,self.chapterId] orderBy:nil];
    if (recharge) {
        return recharge.readPermissions;
    }else{
        NSMutableArray *chapterArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[[PathHelper documentDirectoryPathWithName:@"db"]
                                                                                   stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ChapterInfo",self.articleid]]];
        for (BookChapterInfo *chapterInfo in chapterArray) {
            if ([chapterInfo.chapterId isEqualToString:self.chapterId]) {
                if ([chapterInfo.is_vip isEqualToString:@"0"] ) {
                    self.readPermissions = YES;
                    [self updateBookReadPermissions];
                    return YES;
                }else{
                    break;
                }
            }
        }
        return NO;
    }
}
@end
